//DOM加载完成后执行
if (document.readyState === "loading") {
    document.addEventListener("DOMContentLoaded", () => {
        curDate();
        navChange();
        bannerMove();
        fetchNews();
        topicMove();
    });
} else {
    curDate();
}


/**
 * 异步设置当前页面显示日期
 */
function curDate() {

    let dateSpan = document.querySelector(".top_nav span");
    let myDate = new Date();
    let year = myDate.getFullYear();
    let month = myDate.getMonth() + 1;
    let date = myDate.getDate();
    let week = myDate.getDay();
    let strWeek = ['日', '一', '二', '三', '四', '五', '六'];
    let strDate = `${year}年${month}月${date}日 星期${strWeek[week]}`
    dateSpan.textContent = strDate;
}

/**
 * 导航菜单的“首页”颜色控制
 */
function navChange() {
    let target = document.querySelector("nav");
    let homePage = document.querySelector("nav li a");
    target.onmouseover = function (e) {
        /** @type {HTMLElement} */
        let choiceElement = e.target;
        if(choiceElement.innerHTML !== homePage.innerHTML){
            homePage.style.color = "#333";
            homePage.style.backgroundColor = "transparent";
        }

    }
    target.onmouseout = function(){
        homePage.style.color= "#fff";
        homePage.style.backgroundColor = "#89211b";
    }

}

/**
 * 宣传图片控制
 */
function bannerMove() {
    let delayTime = 6000;
    let timer = null;
    /**@type {HTMLElement}*/
    let target = document.querySelector(".banner_list");
    /**@type {HTMLElement}*/
    let prev = document.querySelector("a.prev");
    /**@type {HTMLElement}*/
    let next = document.querySelector("a.next");


    if (target.childElementCount > 1) {
        timer = setInterval(rightMove, delayTime);
    }

    function leftMove() {
        /**@type {HTMLElement}*/
        // let viewElement = target.children[0];
        // viewElement.style.marginLeft = `-${count*120}rem`;
        // viewElement.style.transition = "margin-left 3s";
        // count++;
        // count %= target.childElementCount;
        let viewElement = target.children[0];
        viewElement.style.marginLeft = "0";
        viewElement.style.transition = "margin-left 4s";
        target.lastElementChild.style.marginLeft = "-120rem";
        target.insertBefore(target.lastElementChild, target.firstElementChild);
    }

    function rightMove() {
        /**@type {HTMLElement}*/
        // let viewElement = target.children[0];
        // viewElement.style.marginLeft = `-${count*120}rem`;
        // viewElement.style.transition = "margin-left 3s";
        // count++;
        // count %= target.childElementCount;
        let viewElement = target.children[1];
        viewElement.style.marginLeft = "-120rem";
        viewElement.style.transition = "margin-left 4s";
        target.firstElementChild.style.marginLeft = "0";
        target.append(target.firstElementChild);
    }

    prev.onmouseover = next.onmouseover = function () {
        clearInterval(timer);
    }

    prev.onmouseout = next.onmouseout = function () {
        timer = setInterval(rightMove, delayTime);
    }

    prev.onclick = function () {
        leftMove();
    }

    next.onclick = function () {
        rightMove();
    }
}

/**
 * 获取新闻信息
 */
function fetchNews() {
    let target = document.querySelector(".news article ul:last-of-type");
    target.innerHTML = "";
    let url = "./data/db.json";
    let xhr = new XMLHttpRequest();
    xhr.open("get", url);
    xhr.send();
    xhr.onload = function () {
        if (xhr.status === 200) {
            console.log("数据获取完成！");
            let data = JSON.parse(xhr.responseText).news;
            for (let i = 0; i < data.length; i++) {
                target.innerHTML += `                <li><a href="#">${cutString(data[i].title, 50)}</a><span>[${getDate(data[i].date)}]</span></li>\n`;
            }
            // console.log(target);
        } else {
            console.log("数据无法获取!");
        }
    };

    xhr.onerror = function () {
        console.log("网络访问异常！");
    }
}

/**
 * 专题新闻图片轮播
 */
function topicMove() {
    /**@type {HTMLElement} topicArticle */
    let topicArticle = document.querySelector(".topic article");

    /**@type {HTMLElement} topicUl */
    let topicUl = document.querySelector(".topic article ul");

    let delayTime = 200;
    let timer = setInterval(move, delayTime);
    let speed = 10;

    topicUl.style.transition = `left 0.2s linear`;

    topicArticle.onmouseover = function () {
        if (timer) {
            clearInterval(timer);
        }
    }
    topicArticle.onmouseout = function () {
        timer = setInterval(move, delayTime);
    }

    function move() {
        console.log(`${topicUl.offsetLeft} + ${topicUl.offsetLeft + topicUl.scrollWidth} >= ${topicArticle.offsetWidth}`);
        if (topicUl.offsetLeft >= 0) {
            speed *= -1;
        }
        if (topicUl.offsetLeft + topicUl.scrollWidth <= topicArticle.offsetWidth) {
            speed *= -1;
        }

        topicUl.style.left = `${topicUl.offsetLeft + speed}px`;

    }

}

function getDate(ms) {
    let d = new Date(ms);
    let month = (d.getMonth() + 1).toString().padStart(2, "0");
    let date = (d.getDate()).toString().padStart(2, "0");
    return `${month}-${date}`
}

function cutString(str, len) {
    //length属性读出来的汉字长度为1 
    if (str.length * 2 <= len) {
        return str;
    }

    var strlen = 0;
    var s = "";
    for (var i = 0; i < str.length; i++) {
        s = s + str.charAt(i);
        if (str.charCodeAt(i) > 128) {
            strlen = strlen + 2;
            if (strlen >= len) {
                return s.substring(0, s.length - 1) + "...";
            }
        } else {
            strlen = strlen + 1;
            if (strlen >= len) {
                return s.substring(0, s.length - 2) + "...";
            }
        }
    }
    return s;
} 